<template>
  <div class="global-field">
    <page-box>
      <template #top>
        <alert-msg content="全局字段可用于客户、工单、动态表单等模块，提高不同业务场景下的协同效率">
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="form" @onSearchFun="searchFun"></search-form>
      </template>
      <template #btn>
        <el-button @click="searchFun">查询</el-button>
        <el-button @click="addField('add', {})" type="primary"> 新建 </el-button>
      </template>
      <template #table>
        <resize-table
          :headers="tableHeaders"
          :data="tableData"
          :pagingData="pagingData"
          @onPageChange="handleCurrentChange"
          @onPageSizeChange="handleSizeChange"
          :showPagination="true"
        >
          <!-- 类型 -->
          <template #type="{ scope }">
            <span>{{ typeAllMap[scope.row.type] }}</span>
          </template>
          <!-- 更新时间 -->
          <template #updateTime="{ scope }">
            <span v-if="scope.row.category === 'system'">系统预置</span>
            <span v-else>{{ scope.row.updateTime }}</span>
          </template>
          <!-- 更新人 -->
          <template #updateAgent="{ scope }">
            <span v-if="scope.row.category === 'system'">系统预置</span>
            <span v-else>{{ scope.row.updateAgent }}</span>
          </template>
          <!-- 状态 -->
          <template #status="{ scope }">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :disabled="scope.row.category === 'system'"
              @change="changeStatus(scope.row)"
              inline-prompt
            />
          </template>
          <!-- 操作 -->
          <template #oprate="{ scope }">
            <span class="btn" @click="addField('edit', scope.row)">编辑</span>
            <span class="btn" v-if="scope.row.category !== 'system'" @click="deleteField(scope.row)">删除</span>
          </template>
        </resize-table>
      </template>
    </page-box>
    <add-edit-field ref="fieldDialog" @onUpdateFieldList="getFieldsFun"></add-edit-field>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, markRaw, onMounted, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { delField, getFields, fieldStatus } from '@app/base/apis/global-field'
import { commonStore } from '@/common/store/modules/common'
import searchForm from '@/common/components/base-form/form.vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import alertMsg from '@common/components/alert/index.vue'
import addEditField from './components/add-edit-field.vue'
import pageBox from '@common/components/page-box.vue'
import { typeAllMap, typeArr } from './type'
import mcCache from '@/common/utils/mc-get-cache'
import deleteIcon from '@/common/components/delete-icon/index.vue'
interface State {
  fieldList: Record<string, unknown>[]
  form: Record<string, unknown>
  tableHeaders: Record<string, unknown>[]
  tableData: Record<string, unknown>[]
  pagingData: Record<string, number>
  init: boolean
}

const instance: any = getCurrentInstance()

const statusChoices: Record<string, unknown>[] = [
  { value: 1, label: '启用' },
  { value: 0, label: '停用' }
]

const getAgentName = (id: string) => {
  const obj = commonStore().publicCache.userCacheObj[id] || {}
  if (obj.agentName) {
    return obj.agentName + '[' + obj.agentNumber + ']'
  }
  return '--'
}

const state: State = reactive({
  fieldList: [
    {
      name: '字段名称',
      field: 'name',
      type: 'text'
    },
    {
      name: '字段类型',
      field: 'type',
      type: 'dropdown',
      multiple: true,
      choices: typeArr('all')
    },
    {
      name: '字段状态',
      field: 'status',
      type: 'dropdown',
      choices: statusChoices
    }
  ],
  form: {
    type: []
  },
  tableHeaders: [
    { label: '字段名称', prop: 'name', show: true },
    { label: '字段类型', prop: 'type', show: true, custom: true },
    { label: '更新时间', prop: 'updateTime', show: true, custom: true },
    { label: '更新人', prop: 'updateAgent', show: true, custom: true },
    { label: '状态', prop: 'status', show: true, custom: true },
    { label: '操作', prop: 'oprate', show: true, width: 160 }
  ],
  tableData: [],
  pagingData: {
    page: 1,
    total: 0,
    limit: 10
  },
  init: true
})

const handleCurrentChange = (page: number) => {
  state.pagingData.page = page
  getFieldsFun()
}

const handleSizeChange = (size: number) => {
  state.pagingData.limit = size
  getFieldsFun()
}

// 搜索
const searchFun = () => {
  state.pagingData.page = 1
  getFieldsFun()
}

// 新建或更新字段
const addField = async (type: string, row: any) => {
  instance?.refs.fieldDialog.openDialog(type, row)
}

// 启用、停用
const changeStatus = (item: any) => {
  if (state.init) {
    state.init = false
    return
  }
  ElMessageBox.confirm(`请确认是否${item.status ? '启用' : '停用'}该字段？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      const sendData = { status: item.status, field: item.field }
      fieldStatus(sendData).then((res) => {
        if (res.success) {
          ElMessage.success('操作成功')
          searchFun()
          // 更新pinia
          mcCache.$updateCacheBySingleKey(
            'globalFieldCache',
            { field: item.field, key: 'status', value: item.status },
            'field',
            'hasObj'
          )
        }
      })
    })
    .catch(() => {
      searchFun()
    })
}

// 删除字段
const deleteField = (row: any) => {
  ElMessageBox.confirm('删除字段后，该字段在其他应用字段的模块均自动删除，且无法恢复，请确认是否删除？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    icon: markRaw(deleteIcon)
  })
    .then(() => {
      delField({ field: row.field }).then((res) => {
        if (res.success) {
          ElMessage.success('删除成功')
          searchFun()
          // 更新pinia
          mcCache.$deleteCache('globalFieldCache', 'field', row.field, 'hasObj')
        }
      })
    })
    .catch()
}

// 获取字段
const getFieldsFun = () => {
  const sendData = {
    ...state.form,
    limit: state.pagingData.limit,
    page: state.pagingData.page
  }
  getFields(sendData).then((res: any) => {
    if (res.success && res.data) {
      res.data.list.forEach((v: any) => {
        v.updateAgent = getAgentName(v.updateAgent)
      })
      state.tableData = res.data.list || []
      state.pagingData.total = res.data.count || 0
    }
  })
}

onMounted(() => {
  getFieldsFun()
})

const { fieldList, form, tableHeaders, tableData, pagingData } = toRefs(state)
</script>

<style lang="stylus">
.global-field {
  .btn {
    color: var(--mc-main-color);
    cursor: pointer;
    margin-right: 16px;

    &:last-child {
      margin-right: 0px;
    }
  }
}
</style>
